package com.code.leetcode.offer;

/**
 * @author codeDorado
 * @version 1.0
 * @date 2020/7/30 11:18
 */
public class The12 {

    int[][] direction = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
    boolean[][] marked;
    int m, n;
    String word;
    char[][] board;

    public boolean exist(char[][] board, String word) {
        this.m = board.length;
        if (m < 1) return false;
        this.n = board[0].length;
        marked = new boolean[m][n];
        this.word = word;
        this.board = board;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (dfs(i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean dfs(int i, int j, int index) {
        if (index + 1 == word.length()) return board[i][j] == word.charAt(index);
        if (board[i][j] == word.charAt(index)) {
            marked[i][j] = true;
            for (int k = 0; k < 4; k++) {
                int x = i + direction[k][0];
                int y = j + direction[k][1];
                if (isValid(x, y) && !marked[x][y]) {
                    if (dfs(x, y, index + 1)) {
                        return true;
                    }
                }
            }
            marked[i][j] = false;
        }
        return false;
    }


    public boolean isValid(int x, int y) {
        return x >= 0 && x < m && y >= 0 && y < n;
    }

    public static void main(String[] args) {
        The12 the12 = new The12();
        the12.exist(new char[][]{{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}}, "ABCCED");
    }
}
